# -*- coding: utf-8 -*-

#   This file is part of emesene.
#
#    Shortcut plugin is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    Shortcut plugin is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with emesene; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

VERSION = '0.2'

import gtk
import emesenelib.common
import Plugin

class MainClass(Plugin.Plugin):
    '''Main plugin class'''

    def __init__(self, controller, msn):
        '''Contructor'''

        Plugin.Plugin.__init__(self, controller, msn )

        self.description = _('Build your own / shortcut!')
        self.authors = {'Orfeo Ciano':'orfeo18@gmail.com'}
        self.website = ''
        self.displayName = _('Shortcuts')
        self.name = 'Shortcuts'

        self.slash_command = 'sc'
        self.controller = controller
        self.Slash = controller.Slash
        self.config = controller.config
        self.config.readPluginConfig(self.name)
	#TO-DO Read configuration file, then removes the key
	# 'slash' so user cannot see it as entry in table
        if self.config.getPluginValue(self.name,'slash' , '') != '':
	    self.slash_command = self.config.getPluginValue(self.name,\
                'slash' , '')
            del self.config.pluginsConfigDict['Shortcuts']['slash']

    def start(self):
        self.Slash.register(self.slash_command, self.slash_sendMessage,\
            _('ShortCut Command'))
        self.enabled = True

    def stop(self):
        self.Slash.unregister(self.slash_command)
        self.config.setPluginValue(self.name,'slash',self.slash_command)
        self.config.writePluginConfig(self.name)
        self.enabled = False

    def check(self):
        return (True, 'Ok')

    def update(self):
        """Removes from Plugin Values items that contains value == ''
	and renew / command"""
        for key in self.config.pluginsConfigDict['Shortcuts'].keys():
            if self.config.pluginsConfigDict['Shortcuts'][key] == '' :
                del self.config.pluginsConfigDict['Shortcuts'][key]
	
	self.Slash.register(self.slash_command, self.slash_sendMessage,\
            _('ShortCut Command'))

    def slash_sendMessage(self, slash_action):
        """Sends a message taking string from Plugin Values"""
        params = slash_action.getParams()

        if self.config.getPluginValue(self.name, params,'') == '' :
            slash_action.outputText(_("Command not found"))

        else :
            #Let's send the message!
            conversation = slash_action.getConversation()
            conversation.sendMessage(self.config.getPluginValue(self.name,\
                params, '') )

    def configure(self):
        '''display a configuration dialog'''
        l = []

        # name, optionType, label, description, value, options
	l.append( Plugin.Option('slash', str, _('\'Slash\' command\n(without \'/\')'),\
            _('Insert here your / command!'), self.slash_command))

        l.append( Plugin.Option('command', str, _('Parameter'),\
            _('Insert here a parameter'), ''))

        l.append( Plugin.Option('action', str , _('Text Associated'),\
            _('Insert here text connected to your command'), ''))

        l.append( Plugin.Option('custom', dict,\
        _('Leave \'Value\' empty to remove a command'), _('Defined Commands'),\
        None, self.config.pluginsConfigDict['Shortcuts']))

        #Run up your config
        self.configWindow = Plugin.ConfigWindow(_('Config Plugin'),l)        
        response = self.configWindow.run()

        #Get parameters
        if response != None:
            #If parameters are not empty
            if response['command'].value != ''\
                and response['action'].value != '':
                
                if self.config.getPluginValue(self.name,\
                    response['command'].value , ''):
                    #command exists
		    return (False, _('Failed to add Command: Command Exists'))

                else:
                    #go 4 it!!!
                    self.config.setPluginValue(self.name, \
                        response['command'].value, response['action'].value)
            
            if response['slash'].value != ''\
                and not self.Slash.commands.has_key(response['slash'].value):
                #try not to override existing \ commands
		self.Slash.unregister(self.slash_command)
		self.slash_command = response['slash'].value

        #Updates plugin configs
        self.update()
        return True
